package com.old.controller;

import com.old.dto.UserDTO;
import com.old.dto.UserUpdatePwdDTO;
import com.old.entity.User;
import com.old.result.PageBean;
import com.old.result.Result;
import com.old.service.UserService;
import com.old.util.JwtUtil;
import com.old.util.Md5Util;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @PostMapping("/user/register")
    public Result register(@RequestBody UserDTO userDTO) {
        if (userDTO.getAccount() == null || userDTO.getPassword() == null || userDTO.getName() == null) {
            return Result.error("缺少必要参数");
        }
        //注册逻辑
        User user = userService.findByAccount(userDTO.getAccount());
        if (user == null) {
            userService.register(userDTO);
            log.info("注册成功，用户名：{}", userDTO.getAccount());
            return Result.success();
        } else {
            log.info("注册失败，用户名已被占用");
            return Result.error("用户名已被占用");
        }
    }

    @PostMapping("/user/login")
    public Result login(@RequestBody UserDTO userDTO) {
        if (userDTO.getAccount() == null || userDTO.getPassword() == null) {
            return Result.error("账号或密码不能为空");
        }
        //登录逻辑
        User user = userService.findByAccount(userDTO.getAccount());
        if (user == null) {
            log.info("登录错误");
            return Result.error("用户名错误");
        }
        if (Md5Util.getMD5String(userDTO.getPassword()).equals(user.getPassword()) && user.getStatus() == userDTO.getStatus()) {
            log.info("登录成功，用户名：{}", userDTO.getAccount());
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username", user.getName());
            claims.put("avatar", user.getAvatar());
            String token = JwtUtil.genToken(claims);
            userService.updateOnlineStatusToTrue(user.getId());
            return Result.success(token);
        }
        return Result.error("密码或身份错误");
    }

    @PostMapping("/user/updatePassword")
    public Result updatePassword(@RequestBody UserUpdatePwdDTO userUpdatePwdDTO) {
        if (userUpdatePwdDTO.getAccount() == null || userUpdatePwdDTO.getName() == null || userUpdatePwdDTO.getNewPassword() == null) {
            return Result.error("缺少必要参数");
        }
        //修改密码逻辑
        User user = userService.findByAccountAndName(userUpdatePwdDTO.getAccount(), userUpdatePwdDTO.getName());
        if (user == null) {
            log.info("修改密码失败，用户名错误");
            return Result.error("用户名错误");
        } else {
            user.setPassword(Md5Util.getMD5String(userUpdatePwdDTO.getNewPassword()));
            userService.save(user);
            log.info("修改密码成功，用户名：{}", userUpdatePwdDTO.getAccount());
            return Result.success();
        }

    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/admin/delUserS")
    public Result deleteByids(@RequestParam List<Integer> ids) {

        userService.deleteByids(ids);
        log.info("删除{}", ids);
        return Result.success();
    }

    /**
     * 删除
     *
     * @param userId
     * @return
     */
    @DeleteMapping("/admin/delUser")
    public Result deleteByid(@RequestParam Integer userId) {

        userService.deleteByUserId(userId);
        log.info("删除{}", userId);
        return Result.success();
    }

    /**
     * /admin/getUserList
     * 获取用户列表
     */
    @GetMapping("/admin/getUserList")
    public Result getUserList(@RequestParam(defaultValue = "1") Integer pageNo,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(required = false) Integer sortBy,
                              @RequestParam(required = false) String searchTerms) {
        PageBean pageList  = userService.getUserList(pageNo, pageSize, sortBy, searchTerms);
        log.info("分页查询: 页码={} 页大小={} 搜索词={} 排序方式={} 总数={}", pageNo, pageSize, searchTerms, sortBy, pageList.getTotal());
        return Result.success(pageList);
    }

    /**
     * /admin/getOnline
     * 获取在线用户
     */
    @GetMapping("/admin/getOnline")
    public Result getOnline() {
        Integer online = userService.getOnline();
        log.info("当前在线人数：{}", online);
        Integer offline = userService.getOffline();
        log.info("当前离线人数：{}", offline);
        Map<String, Object> map = new HashMap<>();
        map.put("online", online);
        map.put("offline", offline);
        return Result.success(map);

    }
}
